package org.blade.personal.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.MapUtils;

public class TreeUtils {

	public static  List getTree(List<Map<String,Object>> list){
		
		//映射id与记录成为  {id : record}
		Map<String,Map> map = new HashMap<String,Map>();
		for(Map su : list){
				map.put(MapUtils.getString(su, "id"), su);
		}
		
		//收集
		Map<String,Map> picking = new HashMap<String,Map>();
		for(Map su : list){
			String parentId = MapUtils.getString(su, "parent_id");
			boolean removed =  MapUtils.getBoolean(su, "removed",false);
			if("0" .equals(parentId)  && !removed){//父id为0，此时为root
				picking.put(MapUtils.getString(su, "id"), su);
				su.put("removed", true);//标记为删除,不可真删除，否则会报currencyXXXX的异常
			}
		}
		
		//构建树
		for(Map su : list){
			String parentId = MapUtils.getString(su, "parent_id");
			boolean removed =  MapUtils.getBoolean(su, "removed",false);
			if(!"0" .equals(parentId) && !removed){
				Map parent = map.get(parentId);//取出映射中的记录
				if(null == parent ){
					su.put("removed", true);
					continue;
				}
				if(parent.containsKey("children") ){//是否有子节点，有把当前记录作为子节点
					List<Map> children = (List<Map>)parent.get("children");
					children.add(su);
					
				}else{//无，则添加子节点容器,再把当前记录作为子节点
					List<Map> children = new ArrayList<Map>();
					children.add(su);
					parent.put("children", children);
				}
				//标记为删除,不可真删除，否则会报currencyXXXX的异常
				su.put("removed", true);
			}
		}
		
		//转为list
		List<Map> result = new ArrayList();
		Set<String> keySet = picking.keySet();
		for(String key : keySet){
			Map resultItem = map.get(key);
			result.add(map.get(key));
		}
		
		return result;
		
	}
}
